package com.jfirer.validator.descriptor;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.metadata.ConstraintDescriptor;
import javax.validation.metadata.ElementDescriptor;
import com.jfirer.validator.util.Commons;
import com.jfirer.validator.util.ConstraintFinderImpl;

public abstract class ElementDescriptorImpl implements ElementDescriptor
{
    protected boolean                      hasConstraints;
    protected Class<?>                     elementClass;
    protected Set<ConstraintDescriptor<?>> constraintDescriptors;
    
    protected void initializeElementDescriptor(Class<?> elementClass, Set<ConstraintDescriptor<?>> constraintDescriptors)
    {
        this.elementClass = elementClass;
        this.constraintDescriptors = constraintDescriptors;
        hasConstraints = constraintDescriptors.isEmpty() == false;
    }
    
    protected Set<ConstraintDescriptor<?>> defineConstraintDescriptors(ConstraintValidatorFactory constraintValidatorFactory,Annotation... annotations)
    {
        Set<ConstraintDescriptor<?>> set = new HashSet<ConstraintDescriptor<?>>();
        for (Annotation annotation : annotations)
        {
            if (Commons.isConstraintAnnotation(annotation))
            {
                set.add(new ConstraintDescriptorImpl<Annotation>(annotation, constraintValidatorFactory));
            }
            else if (Commons.isMutliValueConstraintAnnotation(annotation))
            {
                for (Annotation each : Commons.getMutliValueConstraintAnnotation(annotation))
                {
					set.add(new ConstraintDescriptorImpl<Annotation>(each, constraintValidatorFactory));
                }
            }
        }
        return set;
    }
    
    @Override
    public boolean hasConstraints()
    {
        return hasConstraints;
    }
    
    @Override
    public Class<?> getElementClass()
    {
        return elementClass;
    }
    
    @Override
    public Set<ConstraintDescriptor<?>> getConstraintDescriptors()
    {
        return constraintDescriptors;
    }
    
    @Override
    public ConstraintFinder findConstraints()
    {
        return new ConstraintFinderImpl(constraintDescriptors);
    }
    
}
